//
//  LoginVC.m
//  UHealth
//
//  Created by gjtxz on 15/1/16.
//  Copyright (c) 2015年 gjtx. All rights reserved.
//

#import "LoginVC.h"
#import "iToast.h"
#import "AFNetworking.h"
#import "AppDelegate.h"
#import "NavView.h"
#import "UserObj.h"
#import "DBManage.h"
#import "ForgetVC.h"

@interface LoginVC ()

@property (nonatomic,strong) UITextField    *fieldUser;
@property (nonatomic,strong) UITextField    *fieldPassword;

@end

@implementation LoginVC

-(id)init{
    self = [super init];
    if (self) {
        self.view.backgroundColor = kBacColor;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NavView *nav = [[NavView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, kNavHeight) andTitleStr:kLocal(@"login") andVC:self];
    [self.view addSubview:nav];
    
    
    UILabel *hit1 = [[UILabel alloc]initWithFrame:CGRectMake(20, 5 +kNavHeight, WIDTH-40, 20)];
    hit1.text = kLocal(@"hit2");
    hit1.font = [UIFont systemFontOfSize:12];
    [self.view addSubview:hit1];
    
    NSArray *imgArr = @[@"user",@"password"];
    for (int i = 0; i < 2; i++) {
        UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(23, kNavHeight+33+i*30, 25, 25)];
        img.image = [UIImage imageNamed:imgArr[i]];
        [self.view addSubview:img];
        
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(20, kNavHeight+60+ i*30, WIDTH - 40, 0.5)];
        lineView.backgroundColor = [UIColor grayColor];
        [self.view addSubview:lineView];
    }
    
    _fieldUser = [[UITextField alloc]initWithFrame:CGRectMake(60, kNavHeight+30, WIDTH-80, 30)];
    _fieldUser.font = [UIFont systemFontOfSize:13.0];
    _fieldUser.placeholder = kLocal(@"user");
    _fieldUser.keyboardType = UIKeyboardTypeASCIICapable;
    _fieldUser.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.view addSubview:_fieldUser];
    
    _fieldPassword = [[UITextField alloc]initWithFrame:CGRectMake(60, kNavHeight+60, WIDTH-80, 30)];
    _fieldPassword.font = [UIFont systemFontOfSize:13.0];
    _fieldPassword.placeholder = kLocal(@"password");
    _fieldPassword.keyboardType = UIKeyboardTypeASCIICapable;
    _fieldPassword.secureTextEntry = YES; //密码
    _fieldPassword.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.view addSubview:_fieldPassword];
    
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    loginBtn.frame = CGRectMake(40, kNavHeight+150, WIDTH - 80, 40);
    [loginBtn setTitle:kLocal(@"login") forState:UIControlStateNormal];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginBtn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [loginBtn.layer setMasksToBounds:YES];
    [loginBtn.layer setCornerRadius:1.0];//设置矩形是个圆角半径
    loginBtn.backgroundColor = kBlueColor;
    [self.view addSubview:loginBtn];
    
    UIButton *forgetBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    forgetBtn.frame = CGRectMake(WIDTH-100,loginBtn.frame.origin.y - 35 , 80, 30);
    UILabel *forgetLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, forgetBtn.frame.size.width, forgetBtn.frame.size.height)];
    forgetLabel.tintColor = [UIColor blackColor];
    forgetLabel.font = [UIFont systemFontOfSize:14];
    forgetLabel.text = kLocal(@"forget_pw");
    [forgetBtn addTarget:self action:@selector(forget) forControlEvents:UIControlEventTouchUpInside];
    [forgetBtn addSubview:forgetLabel];
    [self.view addSubview:forgetBtn];
    

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)forget{
    [self presentViewController:[[ForgetVC alloc]init] animated:YES completion:nil];    
}

- (void)BtnClick:(UIButton *)btn
{
    NSString *user = _fieldUser.text;
    NSString *password = _fieldPassword.text;
    
    if (!user.length || !password.length ) {
        [[iToast makeText:kLocal(@"infoHit")] show];
        return;
    }
    [self.view endEditing:YES];
    if (!kNetIsOK) {
        [[iToast makeText:kLocal(@"netNoOk")] show];
        return;
    }
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer.timeoutInterval = 10;
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject: @"text/html"];
    NSString *postStr = [NSString stringWithFormat:@"%@/action/json/login.jsp",kBaseUrl];
    NSDictionary *parameters = @{@"action": @"login",
                                 @"username":user,
                                 @"password":password,
                                 @"jpush_registrationid":kJiGuang,
                                 @"umeng_device_token" :kUMengDeviceToken,
                                 @"mobile_type":@"2",
                                 @"mobile_lng":@"",
                                 @"mobile_lat":@""};
    [manager POST:postStr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //        kDebug(@"Success: %@", operation.responseString);
        BOOL type = [[responseObject objectForKey:@"type"] boolValue];
        if(type){//登录成功
            //{"errorCode":"1","userid":"00022120224","mem_name":"zjw","mem_username":"13049371396","mem_headpic":"http://tukang.hanyouapp.com/upload/201502/12/11-33-20_6535_100.png","mem_type":0,"mem_sex":0,"num":0,"type":true,"msg":"登录成功"}
            
//            NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
//            int userid = [[responseObject objectForKey:@"userid"] intValue];
//            [def setInteger:userid forKey:kNetUserID];//账户ID
//            [def setObject:user forKey:kNetUserName];//账户名
//            [def synchronize];
            NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
            int userid = [responseObject[@"userid"] intValue];
            [def setInteger:userid forKey:kNetUserID];//账户ID
            [def setObject:user forKey:kNetUserName];//账户名
            [def setObject:@"" forKey:kNetUserPhone];//手机
            
            [def synchronize];
            
            UserObj *muser = [[UserObj alloc]init];
            muser.userID    = kNetID;
            muser.famID     = 0;
            muser.headImg   = responseObject[@"mem_headpic"];
            muser.name      = responseObject[@"mem_name"];
            muser.sex       = [responseObject[@"mem_sex"] intValue];
            muser.birthDate = responseObject[@"mem_birth"];
            muser.height    = [responseObject[@"men_shengao"] floatValue];
            muser.weight    = [responseObject[@"men_tizhong"] floatValue];
            //主账号 插入或者更新
            [[DBManage sharedManager]insertData:muser andTable:kUserTable];
            
            AppDelegate *delegate = [UIApplication sharedApplication].delegate;
            [delegate changRootVCToMain];

            
        }else{
        }
        [[iToast makeText:[responseObject objectForKey:@"msg"]] show];
        //        [[NSFileManager defaultManager] removeItemAtPath:kPostImgFilePath error:nil];//删除图片
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        kDebug(@"Error: %@", error);
        [[iToast makeText:kLocal(@"netError")] show];
        //        [[NSFileManager defaultManager] removeItemAtPath:kPostImgFilePath error:nil];//删除图片
    }];
    
    
}



- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
